<template>
    <div>
        <!-- 搜索栏 -->
        <el-card class="!border-none mb-4" shadow="never">
            <el-form class="mb-[-16px]" :model="queryParams" :inline="true">
                <el-form-item label="文档内容">
                    <div class="w-[250px]">
                        <el-input
                            v-model="queryParams.name"
                            placeholder="请输入文档内容搜索"
                            clearable
                            @keyup.enter="resetPaging"
                        />
                    </div>
                </el-form-item>
                <el-form-item label="拥有者">
                    <el-input
                        v-model="queryParams.user"
                        class="w-[250px]"
                        placeholder="请输入用户信息"
                        clearable
                        @keyup.enter="resetPaging"
                    />
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" @click="resetPaging">查询</el-button>
                    <el-button @click="resetParams">重置</el-button>
                </el-form-item>
            </el-form>
        </el-card>

        <!-- 表格栏 -->
        <el-card v-loading="pager.loading" shadow="never" class="!border-none mt-4">
            <div class="mt-[-14px]">
                <el-tabs v-model="queryParams.status" @tab-change="resetPaging()">
                    <el-tab-pane
                        v-for="item in tabsList"
                        :label="`${item.name}(${pager.extend?.[item.key] || 0})`"
                        :name="item.type"
                        :key="item.type"
                    />
                </el-tabs>
            </div>
            <div>
                <el-button
                    :disabled="selectData.length <= 0"
                    v-perms="['agent:know:dataset:delete']"
                    @click="handleDelete(selectData)"
                    class="!mb-4"
                >
                    批量删除
                </el-button>
                <el-button
                    :disabled="selectData.length <= 0"
                    v-perms="['agent:know:dataset:retry']"
                    @click="handleRetry(selectData)"
                    class="!mb-4"
                >
                    失败重试
                </el-button>
            </div>
            <el-table :data="pager.lists" size="large" @selection-change="handleSelectionChange">
                <el-table-column type="selection" width="55" />
                <el-table-column label="序号" min-width="60">
                    <template #default="{ $index }">
                        {{ $index + 1 }}
                    </template>
                </el-table-column>
                <el-table-column label="拥有者" prop="user" min-width="165">
                    <template #default="{ row }">
                        <div class="flex items-center">
                            <el-avatar :size="50" :src="row?.user?.avatar" class="shrink-0" />
                            <div class="grid ml-2">
                                <p class="line-clamp-1">{{ row?.user?.nickname }}</p>
                                <el-popover
                                    :content="row?.user?.sn"
                                    effect="dark"
                                    placement="top-start"
                                >
                                    <template #reference>
                                        <p class="text-xs text-tx-placeholder line-clamp-1">
                                            {{ row?.user?.sn }}
                                        </p>
                                    </template>
                                </el-popover>
                            </div>
                        </div>
                    </template>
                </el-table-column>
                <el-table-column label="向量内容" prop="question" min-width="150">
                    <template #default="{ row }">
                        <div class="line-clamp-3">{{ row?.question }}</div>
                    </template>
                </el-table-column>
                <el-table-column label="补充内容" prop="answer" min-width="150">
                    <template #default="{ row }">
                        <div class="line-clamp-3">{{ row?.answer || '-' }}</div>
                    </template>
                </el-table-column>
                <el-table-column label="字符总数" prop="character" min-width="100" />
                <el-table-column label="消耗积分" prop="use_points" min-width="100" />
                <el-table-column label="消耗Tokens" prop="use_tokens" min-width="100" />
                <el-table-column label="所属知识库" prop="know" min-width="150">
                    <template #default="{ row }">
                        <el-tag type="info">
                            <el-popover placement="right" width="220px" trigger="hover">
                                <div>
                                    <span class="mr-2">知识库名: </span>
                                    <span>{{ row?.know }}</span>
                                </div>
                                <div class="mt-[10px]">
                                    <span class="mr-2">向量别名: </span>
                                    <span>{{ row?.vector_alias }}</span>
                                </div>
                                <div class="mt-[10px]">
                                    <span class="mr-2">向量模型: </span>
                                    <span>{{ row?.vector_model }}</span>
                                </div>
                                <template #reference>
                                    {{ row?.know || '无' }}
                                </template>
                            </el-popover>
                        </el-tag>
                    </template>
                </el-table-column>
                <el-table-column label="学习状态" prop="status" min-width="100">
                    <template #default="{ row }">
                        <el-tag v-if="row.status === 0" type="info">等待学习</el-tag>
                        <el-tag v-if="row.status === 1" type="primary">正在排队</el-tag>
                        <el-tag v-if="row.status === 2" type="warning">正在学习</el-tag>
                        <el-tag v-if="row.status === 3" type="success">学习成功</el-tag>
                        <el-tag v-if="row.status === 4" type="danger" class="cursor-pointer">
                            <popup title="失败原因" cancelButtonText="" confirmButtonText="">
                                <template #trigger>学习失败</template>
                                <div class="text-error p-2">{{ row?.error || '-' }}</div>
                            </popup>
                        </el-tag>
                        <p
                            v-if="row.error"
                            class="mt-0.5 text-xs text-error line-clamp-3"
                        >
                            原因: {{ row?.error }}
                        </p>
                    </template>
                </el-table-column>
                <el-table-column label="更新时间" prop="update_time" min-width="180" />
                <el-table-column label="操作" width="140" fixed="right">
                    <template #default="{ row }">
                        <el-button
                            v-perms="['agent:know:dataset:detail']"
                            type="primary"
                            link
                            @click="handleView(row)"
                        >
                            查看
                        </el-button>
                        <el-button
                            v-perms="['agent:know:dataset:delete']"
                            type="danger"
                            link
                            @click="handleDelete([row.id])"
                        >
                            删除
                        </el-button>
                    </template>
                </el-table-column>
            </el-table>
            <div class="flex justify-end mt-4">
                <paging v-model="pager" @change="queryLists" />
            </div>
        </el-card>

        <pop-data-view
            v-if="dataState.show"
            :show="dataState.show"
            :uuid="dataState.uuid"
            @close="dataState.show = false"
        />
    </div>
</template>

<script setup lang="ts">
import { usePaging } from '@/hooks/usePaging'
import feedback from '@/utils/feedback'
import knowDatasetApi from '@/api/agent/know/dataset'
import PopDataView from './_components/_pop_data_view.vue'

// 选项列表
const tabsList = reactive([
    {
        type: '',
        name: '全部',
        key: 'train_all_count'
    },
    {
        type: 0,
        name: '等待学习',
        key: 'train_wait_count'
    },
    {
        type: 2,
        name: '学习中',
        key: 'train_ing_count'
    },
    {
        type: 3,
        name: '学习成功',
        key: 'train_yes_count'

    },
    {
        type: 4,
        name: '学习失败',
        key: 'train_fail_count'
    }
])

// 当前数据
const dataState = reactive({
    uuid: '',
    show: false
})

// 查询参数
const queryParams = reactive({
    name: '',
    user: '',
    status: ''
})

// 分页查询
const { pager, queryLists, resetParams, resetPaging } = usePaging({
    fetchFun: knowDatasetApi.lists,
    params: queryParams
})

/**
 * 表格勾选
 */
const selectData = ref<string[]>([])
const handleSelectionChange = (val: any[]) => {
    selectData.value = val.map((item) => item.id)
}

/**
 * 查看详情
 *
 * @param row
 */
const handleView = (row: any) => {
    dataState.uuid = row.id
    dataState.show = true
}

/**
 * 处理删除
 *
 * @param {string[]} uuids
 * @returns {Promise<void>}
 */
const handleDelete = async (uuids: string[]): Promise<void> => {
    feedback.confirm('确定要删除此项数据吗?')
        .then(async () => {
            await knowDatasetApi.delete(uuids)
            feedback.msgSuccess('删除成功')
            await queryLists()
        }).catch(() => {})
}

/**
 * 处理删除
 *
 * @param {string[]} uuids
 * @returns {Promise<void>}
 */
const handleRetry = async (uuids: string[]): Promise<void> => {
    feedback.confirm('确定要重新尝试训练吗?')
        .then(async () => {
            await knowDatasetApi.retry(uuids)
            feedback.msgSuccess('操作成功')
            await queryLists()
        }).catch(() => {})
}

onMounted(async () => {
    await queryLists()
})
</script>